package com.ctu.study
{
	import __AS3__.vec.Vector;
	
	import flash.events.EventPhase;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.text.engine.*;
	
	import mx.containers.Box;
	import mx.core.UIComponent;
	
	
	public class TextWrapper extends UIComponent
	{
		private var tb:TextBlock; 
		private var box:Box;
		private var point:Point;
		private var textLineArr:Array;
		//private var str:String = "원·달러 환율은 크게 떨어지고 있습니다. 오전 11시 현재 서울외환시장에서 달러화에 대한 원화의 환율은 지난주 금요일 보다 25원 정도 급락한 1,340원선에서 거래되고 있습니다. ";
		private var str:String = "Greasemonkey and Fluid userscripts. AIR and the new Titanium apps. Browser add-ons. When you go to a website do you know if you are getting the best experience for you? You could search for script on userscripts";
		private var str1:String = "or Google for apps, but what if the developers of the sites had a way of pointing out that there were enhanced experiences for you?";
		public function TextWrapper(x:int, y:int, w:int, h:int)
		{
			this.x = x;
			this.y = y;
			this.width = w;
			this.height = h;
			textLineArr = new Array();
			point = new Point();
			var boundBox:Box = new Box;
			boundBox.x = 0;
			boundBox.y = 0;
			boundBox.width = 500;
			boundBox.height = 300;
			boundBox.setStyle("backgroundColor", 0xFAFAFA);
			addChild(boundBox);
			
			// Add Image
			box = new Box;
			box.x = 100;
			box.y = 0;
			box.width = 50;
			box.height = 30;
			box.setStyle("backgroundColor", 0xFF0000);
			box.alpha = 0.7;
			
			box.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			
			addChild(box);
			
			// Add Text Lines
			trace("TextWrapper start");
			tb = new TextBlock();
			var fd:FontDescription = new FontDescription();
			fd.fontName = "Trebuchet MS";
			fd.fontLookup = flash.text.engine.FontLookup.DEVICE;
			var ef:ElementFormat = new ElementFormat(fd);
			var ef1:ElementFormat = new ElementFormat(fd);
			ef.fontSize = 16;
			ef1.fontSize = 20;
			ef1.color = 0xFF0000;
			ef1.breakOpportunity = flash.text.engine.BreakOpportunity.ANY;
			//ef.alignmentBaseline = flash.text.engine.TextBaseline.IDEOGRAPHIC_CENTER;
			ef.breakOpportunity = flash.text.engine.BreakOpportunity.ANY;
			//var str:String = "The Flex Gumbo MAX Preview Language Reference provides syntax and usage information for every element in the ActionScript™ language. It documents all elements in Adobe® Flash® Player and Adobe® AIR™ that are officially supported by Adobe. ";
			var block:Vector.<ContentElement> = new Vector.<ContentElement>();
			block.push(new TextElement(str, ef));
			block.push(new TextElement(str1, ef1));
			
			var gl:GroupElement = new GroupElement();
			gl.setElements(block);
			tb.content = gl;
			redrawText(null);
			
			for(var i:int=0;i<textLineArr.length;i++){
				var tl:TextLine = textLineArr[i];
				trace(tl.getBounds(this));
			}
			trace("TextWrapper end");
		}
		
		private function onMouseDown(event:MouseEvent):void {
			trace("onMouseDown");
			if(event.eventPhase != EventPhase.AT_TARGET){
				return;
			}
			point.x = this.mouseX;
			point.y = this.mouseY;
			this.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
		}
		
		private function onMouseUp(event:MouseEvent):void {
			trace("onMouseUp");
			if(this.hasEventListener(MouseEvent.MOUSE_MOVE))
				this.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			
			redrawText(event);
		}
		
		private function onMouseMove(event:MouseEvent):void {
			trace("onMouseMove");
			box.x += this.mouseX - point.x;
			box.y += this.mouseY - point.y;
			point.x = this.mouseX;
			point.y = this.mouseY;
			event.updateAfterEvent();
		}
		
		private function redrawText(event:MouseEvent):void {
			trace("redraw");
			// clean up
			trace("list length:"+textLineArr.length);
			for(var i:int = 0; i<textLineArr.length;i++){
				removeChild(textLineArr[i]);
			}
			textLineArr = new Array();
			
			// image boundary
			var imgBound:Rectangle = box.getBounds(this);
			trace("image bound:"+imgBound + " specified dim:"+box.width+"/"+box.height);
			
			// reposition the lines again
			var lineWidth:Number = 500;
			var verticalPosition:Number = 0;
            var xPos:Number = 0;
            var yPos:Number = 0;
			var firstLine:TextLine = null;
			var textLine:TextLine = null;
			var isSplitted:Boolean = false;
			var isLeftSpace:Boolean = false;

			firstLine = tb.createTextLine(null, lineWidth);
			firstLine.x = xPos;
			firstLine.y = yPos;

			var lineBound:Rectangle = firstLine.getBounds(this);
			lineBound.x = lineBound.x + 100;
			lineBound.y = lineBound.y + 100;
			
			var hitStatus:Boolean = imgBound.intersects(lineBound);
			trace("line bound:"+lineBound+" hitStatus:"+hitStatus);
			
			if(hitStatus){
				lineWidth = imgBound.x;
				firstLine = tb.createTextLine(null, lineWidth); // create again
				isSplitted = true;
				if(imgBound.x + imgBound.width + 25 < 500){
					isLeftSpace = true;
					xPos = imgBound.x + imgBound.width;
					yPos = 0;
				} else { 
					isLeftSpace = false;
					xPos = 0;
					yPos = yPos + firstLine.height + 4; // line spacing 4
				} 				
			} else {
				isSplitted = false;
				xPos = 0;
				yPos = yPos + firstLine.height + 4;
			}
			
			addChildAt(firstLine, this.numChildren-1);
			textLineArr.push(firstLine);
			
			textLine = firstLine;
			
			var tmpPos:Point = new Point();
			var cnt:int = 0;
			
			trace("line dim:"+xPos+"/"+yPos);
			
			
			while(textLine){
				cnt++;
				tmpPos.x = xPos;
				tmpPos.y = yPos;
				
				//if(cnt == 2) break;
				if(isLeftSpace){
					lineWidth = 500 - imgBound.x - imgBound.width;
					textLine = tb.createTextLine(textLine, lineWidth);
					if(textLine == null) break;
					textLine.x = xPos;
					textLine.y = yPos;
					
					xPos = 0;
					yPos = yPos + textLine.height + 4;
					
					isLeftSpace = false;
					isSplitted = false;
				} else {
					// do hit test
					lineWidth = 500;
					textLine = tb.createTextLine(textLine, lineWidth);	
					if(textLine == null) break;			
					textLine.x = xPos;
					textLine.y = yPos;
					
					lineBound = textLine.getBounds(this);
					lineBound.x = lineBound.x + 100;
					lineBound.y = lineBound.y + 100;
					hitStatus = imgBound.intersects(lineBound);
					trace("line bound:"+lineBound+" hitStatus:"+hitStatus);
					
					if(hitStatus){
						lineWidth = imgBound.x;
						textLine = tb.createTextLine(textLine.previousLine, lineWidth); // create again
						isSplitted = true;
						if(imgBound.x + imgBound.width + 25 < 500){
							isLeftSpace = true;
							xPos = imgBound.x + imgBound.width;
							yPos = yPos;
						} else { 
							isLeftSpace = false;
							xPos = 0;
							yPos = yPos + textLine.height + 4; // line spacing 4
						} 				
					} else {
						isSplitted = false;
						xPos = 0;
						yPos = yPos + textLine.height + 4;
					}
				}
				
				textLine.x = tmpPos.x;
				textLine.y = tmpPos.y;
							
				addChildAt(textLine, this.numChildren-1);
				textLineArr.push(textLine);
			}
		}
	}
}